<?php
/**
 * Created by PhpStorm.
 * User: pufan
 * Date: 16/6/29
 * Time: 下午3:48
 */

namespace Library\Task;


class DbTask extends Task
{
    /*
     * 增加任务
     * @param  $taskId 任务标识
     * @param  $data 任务运行的sql 语句
     * @param  $time 为年月日时分秒, 例如"16-06-29 18:57:52"
     */
    function add($taskId,  $data, $time) {
        try {
            $order = D();
            $taskId = C('TASK_PREFIX').$taskId;
            $sql = 'CREATE DEFINER=`'.C('DB_USER').'`@`%` EVENT `'.$taskId.'` ON SCHEDULE AT "'.$time.'" 
                    ON COMPLETION NOT PRESERVE ENABLE DO '.$data;

            $result = $order->execute($sql);
        } catch (\Exception $e) {
            $result = FALSE;
            \Think\Log::record('add Task catch Exception'.$e->getMessage());
            return false;
        }
        return true;
    }

    /*
     * 删除任务
     * @param  $taskId 任务标识
     */
    function del($taskId) {
        try {
            $order = D('');
            $taskId = C('TASK_PREFIX').$taskId;

            $sql = 'drop event '.$taskId;
            $result = $order->execute($sql);
        } catch (\Exception $e) {
            $result = FALSE;
            \Think\Log::record('del Task catch Exception'.$e->getMessage());
            return false;
        }
        return true;
    }

    /*
     * 更新任务时间
     * @param  $taskId 任务标识
     * @param  $time 为年月日时分秒, 例如"16-06-29 18:57:52"
     */
    function updateTime($taskId, $time) {
        try {
            $order = D('');
            $taskId = C('TASK_PREFIX').$taskId;

            $sql = 'alter event `'.$taskId.'` on schedule AT "'.$time.'"';
            $result = $order->execute($sql);
        } catch (\Exception $e) {
            $result = FALSE;
            \Think\Log::record('updateTime Task catch Exception'.$e->getMessage());
            return false;
        }
        return true;
    }
}